import React, { memo, useEffect, useRef, useState } from 'react';
import {
  ConfigProvider,
  Divider,
  Table,
  Modal,
  Button,
  Popconfirm,
  Space,
  Dropdown,
  message,
  Menu,
} from 'antd';
import { ProForm } from '@/base-ui';
import DivWrapper from './style';
import zhCN from 'antd/es/locale/zh_CN';
import http from '@/services/request';
import store from '@/pages/home/store';
import {
  PageSearchConfig,
  SearchSelector,
  DataType,
  UseSearch,
} from './config';
import { action3, action4 } from '@/pages/home/createAction';
import moment from 'moment';
import ButtonGroup from './components/ButtonGroup';
import CreateForm from './components/CreateForm';
import DescriptionsDrawer from './components/DescriptionsDrawer';

interface IPropsConnect {
  fetchProductionPlanList: (payload: any) => void;
  productionPlanList: any;
}

const Production_Plan = memo((props: IPropsConnect) => {
  const { productionPlanList, fetchProductionPlanList } = props;
  const [ dataSource, setdataSource ]: any = useState([]);
  //更多功能定位id
  const [DrawerId, setDrawerId]: any = useState({});
  //抽屉开关
  const [DrawerVisible, setDrawerVisible] = useState(false);
  //复选框批量删除
  const [itemSelected, setItemSelected] = useState<React.Key[]>([]);
  //是否新增
  const [edited, setedited]: any = useState({});
  //高级检索
  const [isMoreSearchShow, setisMoreSearchShow]: any = useState(false);
  const newref: any = useRef();
  const [searchMore, setSearchMore] = useState(false);

  useEffect(() => {
    getProductionPlanList();
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const getProductionPlanList = () => {
    http
      .get('/server/productionPlanSlaughter/list/1/100')
      .then((res) => {
        fetchProductionPlanList(res.data);
      });
  }

  //复选框的内容设定
  const rowSelection = {
    onChange: (selectedRowKeys: React.Key[], selectedRows: DataType[]) => {
      let res: any[] = [];
      selectedRows.map((i) => res.push(i.id));
      setItemSelected(res);
    },
    getCheckboxProps: (record: DataType) => ({
      disabled: record.name === 'Disabled User', // Column configuration not to be checked
      name: record.name
    })
  };

  //批量删除
  const deleteItems = () => {
    http({
      url: `/server/productionPlanSlaughter/deletion/batch`,
      method: 'delete',
      data: JSON.stringify(itemSelected),
      headers: { 'Content-Type': 'application/json' }
    }).then((res: any) => {
      getProductionPlanList();
    });
  };

  //导出
  const exported = () => {
    http({
      method: 'get',
      url: '/server/dailySlaughter/export',
      data: JSON.stringify([1, 4]),
      responseType: 'blob',
      headers: {
        'Content-Type': 'application/json'
      }
    }).then((res: any) => {
      const blob = new Blob([res.data], {
        // res 为后台返回数据
        type: 'application/vnd.ms-excel;charset=utf-8' // 导出数据生成excel的格式设置
      });
      if ('download' in document.createElement('a')) {
        // 非IE下载
        const elink = document.createElement('a');
        elink.download = Date.now() + `.xlsx`;
        elink.style.display = 'none';
        elink.target = '_blank';
        elink.href = window.URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click();
      }
    });
  };
  //获取时间
  const Time = (
    time: {
      getDate: () => any;
      getUTCFullYear: () => any;
      getHours: () => any;
      getMonth: () => number;
      getMinutes: () => any;
      getSeconds: () => any;
    },
    search?: boolean
  ) => {
    const date = time.getDate();
    const year = time.getUTCFullYear();
    const hours = time.getHours();
    const month = time.getMonth() + 1;
    const minutes = time.getMinutes();
    const seconds = time.getSeconds();
    const a = [year, month, date].join('-');
    const b = [hours, minutes, seconds].join(':');
    if (search === true) {
      return a;
    }
    return [a, b].join(' ');
  };
  // 控制对话框显示（新增）
  const [addModalVisible, setAddModalVisible] = useState(false);
  // 对话框确认
  const handleAddModalOk = () => {
    setAddModalVisible(false);
    //如果id存在--就是修改
    if (store.getState().name === '编辑') {
      const newedited = newref.current.getFieldsValue();

      http
        .put(`/server/productionPlanSlaughter/update/${edited}`, {
          ...newedited,
          bookDate: moment(newedited.bookDate).format('yyyy-MM-DD HH:mm:ss'),
          productionCompletionDate: moment(
            newedited.productionCompletionDate
          ).format('yyyy-MM-DD HH:mm:ss')
        })
        .then(() => {
          getProductionPlanList();
        });
      return;
    }
    //id不在--就是新增
    else {
      const addData = newref.current.getFieldsValue();
      const {
        bookBroilerParts,
        bookDate,
        customer,
        number,
        productionCompletionDate,
        status,
        totalPrice,
        unitPrice
      } = addData;

      let postData = {
        bookBroilerParts,
        bookDate: Time(bookDate._d),
        customer,
        number: Number(number),
        productionCompletionDate: Time(productionCompletionDate._d),
        status,
        totalPrice: Number(totalPrice),
        unitPrice: Number(unitPrice)
      };
      http
        .post('/server/productionPlanSlaughter/save', postData)
        .then((res: any) => {
          getProductionPlanList();
        });
    }
    setAddModalVisible(false);
  };
  //编辑
  const edit = (item: any) => {
    setAddModalVisible(true);
    setedited(item.id);
    store.dispatch(action3('编辑'));
    //这里如果单单setField..会报错："表单还没挂载调用了setFieldsValue",应该用异步，设一个定时器
    setTimeout(() => {
      newref.current.setFieldsValue({
        //antd 的时间组件必须要用moment给弄入
        ...item,
        bookDate: moment(item.bookDate),
        productionCompletionDate: moment(item.productionCompletionDate)
      });
    }, 0);
  };
  // 对话框取消
  const handleAddModalCancel = () => {
    setAddModalVisible(false);
  };
  const add = () => {
    store.dispatch(action4('新增'));
    setTimeout(() => {
      setTimeout(() => {
        newref.current.setFieldsValue({
          bookBroilerParts: '',
          bookDate: '',
          customer: '',
          number: '',
          orderNumber: '',
          productionCompletionDate: '',
          status: '',
          totalPrice: '',
          unitPrice: ''
        });
      }, 0);
    });
    setAddModalVisible(true);
  };
  const indexTable = {
    pagination: {
      //每页10条项目
      defaultPageSize: 10,
      //自定义每页显示数目
      showSizeChanger: true,
      //自定义每页显示项目的选项
      pageSizeOptions: ['5', '10', '15'],

      // 输入指定页码跳页
      showQuickJumper: true,
      //全部项目数（最好可以用变量表示，与实际项目数关联）
      total: productionPlanList?.length
    }
  };
  //table的数据名
  const FormColumns: any = [
    {
      title: '客户',
      dataIndex: 'customer',
      key: 'customer',
      width: 150
    },
    {
      title: '预订肉鸡部位',
      dataIndex: 'bookBroilerParts',
      key: 'bookBroilerParts',
      width: 150
    },
    {
      title: '预订时间',
      dataIndex: 'bookDate',
      key: 'bookDate',
      width: 150
    },
    {
      title: '生产完成时间',
      dataIndex: 'productionCompletionDate',
      key: 'productionCompletionDate',
      width: 150,

    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 150,

    },
    {
      title: '状态',
      dataIndex: 'number',
      key: 'number',
      width: 150
    },
    {
      title: '单价',
      dataIndex: 'unitPrice',
      key: 'unitPrice',
      width: 150
    },
    {
      title: '总价',
      dataIndex: 'totalPrice',
      key: 'totalPrice',
      width: 150
    },
    {
      title: '操作',
      dataIndex: 'action',
      key: 'action',
      width: 150,
      render: (_: any, record: any) => {
        return (
          <Space>
            {/* eslint-disable-next-line jsx-a11y/anchor-is-valid*/}
            <a onClick={() => edit(record)}>编辑</a>
            <Popconfirm
              title="确定删除?"
              okText="确认"
              cancelText="取消"
              // cancelButtonProps={{ size: 'middle' }}
              onConfirm={() => {
                http
                  .delete(`/server/productionPlanSlaughter/delete/${record.id}`)
                  .then(() => {
                    const newData = productionPlanList.filter(
                      (item: { id: any }) => item.id !== record.id
                    );
                    fetchProductionPlanList(newData);
                  });
              }}
            >
              {/* eslint-disable-next-line jsx-a11y/anchor-is-valid*/}
              <a style={{ color: '#ff4d4f' }}>删除</a>
            </Popconfirm>
            <Dropdown overlay={menu(record)}>
              {/* eslint-disable-next-line jsx-a11y/anchor-is-valid*/}
              <a
                onClick={(e) => {
                  e.preventDefault();
                }}
              >
                ···
              </a>
            </Dropdown>
          </Space>
        );
      },
      fixed: 'right'
    }
  ];
  const menu = (item: any) => (
    <Menu
      items={[
        {
          key: 0,
          label: (
            <Button
              type="primary"
              onClick={(e: any) => {
                showDrawer(item);
              }}
            >
              详情
            </Button>
          )
        },

        {
          key: 2,
          label: (
            <Button
              onClick={function () {
                window.print();
              }}
            >
              打印
            </Button>
          )
        }
      ]}
    />
  );
  // 高级检索 条件查询
  const onFinish = (form: any) => {
    //查询的后面传个true即可查日期
    form.bookDate = Time(form.bookDate._d, true);
    // 发送请求
    http.post('/server/productionPlanSlaughter/get', form).then((res: any) => {
      // console.log(res.data,'条件查询');
      if (res.statusCode !== 20000) {
        return message.error('查询失败');
      }
      const data = res.data || [];
      fetchProductionPlanList(data);
    });
  };
  //详情--抽屉
  const showDrawer = (data: any) => {
    setDrawerVisible(true);
    http
      .get(`/server/productionPlanSlaughter/get/${data.id}`)
      .then((res: { data: any }) => {
        setDrawerId(res.data);
      });
  };
  const onDraweClose = () => {
    setDrawerVisible(false);
  };
  return (
    <DivWrapper>
      {searchMore ? (
        <div>
          <ProForm formItems={PageSearchConfig} onFinish={onFinish} />
          <Divider style={{ margin: '10px 0 20px' }} />
        </div>
      ) : null}
      <ButtonGroup
        deleteItems={() => deleteItems()}
        add={() => add()}
        exported={() => exported()}
      />
      <UseSearch
        setisMoreSearchShow={(e: any) => {
          setisMoreSearchShow(e);
        }}
        isMoreSearchShow={isMoreSearchShow}
        setsearchMore={(e: boolean) => setSearchMore(e)}
      />
      <SearchSelector
        dataSource={(e: any) => setdataSource(e)}
        style={{ float: 'right' }}
      />
      <ConfigProvider locale={zhCN}>
        <Table
          dataSource={dataSource?.length !== 0 ? dataSource : productionPlanList}
          columns={FormColumns}
          scroll={{ x: 1300 }}
          pagination={indexTable.pagination}
          rowKey={(i: { id: any }) => i.id}
          rowSelection={{
            type: 'checkbox',
            ...rowSelection
          }}
        />
      </ConfigProvider>
      <DescriptionsDrawer DrawerId={DrawerId} DrawerVisible={DrawerVisible} onDraweClose={onDraweClose}/>
      <Modal
        width={'600px'}
        centered
        bodyStyle={{
          height: '400px',
          display: 'flex',
          flexDirection: 'column-reverse'
        }}
        title="新增记录"
        visible={addModalVisible}
        onOk={handleAddModalOk}
        onCancel={handleAddModalCancel}
      >
        <CreateForm newref={newref} />
      </Modal>
    </DivWrapper>
  );
});

export default Production_Plan;
